/**
 * Description: Unix 本地通信server端 -- 使用UDP协议
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <sys/un.h>

#define N 100

#define ERR(msg) do {          \
            perror(msg);        \
            printf("%s:%s:%d\n", __FILE__, __func__, __LINE__); \
            exit(EXIT_FAILURE); \
        }while(0)


int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Usage %s <socket filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
    char buff[N] = {0};

    struct sockaddr_un serveraddr, clinetaddr;
    serveraddr.sun_family = AF_UNIX;
    strcpy(serveraddr.sun_path, argv[1]);
    socklen_t addr_len = sizeof(serveraddr);

    if (-1 == bind(sockfd, (struct sockaddr *)&serveraddr, addr_len))
    {
        ERR("bind");
    }

    printf("server is ready.\n");

    while(1) {
        bzero(buff, N);

        if (-1 == recvfrom(sockfd, buff, N, 0, (struct sockaddr *)&clinetaddr, &addr_len))
        {
            ERR("recvfrom");
        }

        printf("[from client]: %s\n", buff);

        sprintf(buff, "%s received.\n", buff);
        sendto(sockfd, buff, N, 0, (struct sockaddr *)&clinetaddr, addr_len);
        printf("[to client]:%s\n", buff);
    }


    return 0;
}
